﻿using BUGCOME.Infrastructure.Model;
using BUGCOME.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace BUGCOME.Common
{
    /// <summary>
    /// 阿里云短信服务辅助类，封装短信发送及参数处理功能
    /// </summary>
    public class MobileHelper
    {
        /// <summary>
        /// 短信模板配置信息（包含签名和模板编码）
        /// </summary>
        private readonly MobileOptions mobileOptions = new();

        /// <summary>
        /// 阿里云访问凭证对象（存储AccessKey信息）
        /// </summary>
        private readonly ALiYun aLiYun = new ALiYun();

        /// <summary>
        /// 无参构造函数，从配置文件加载短信服务配置
        /// </summary>
        public MobileHelper()
        {
            List<MobileOptions> options = new();
            AppSettings.Bind("MailOptions", options);
            AppSettings.Bind<ALiYun>("ALiYun", aLiYun);
            mobileOptions = options.First();
        }

        /// <summary>
        /// 带参构造函数，支持外部注入模板配置
        /// </summary>
        /// <param name="_mobileOptions">自定义短信模板配置</param>
        public MobileHelper(MobileOptions _mobileOptions)
        {
            AppSettings.Bind<ALiYun>("ALiYun", aLiYun);
            mobileOptions = _mobileOptions;
        }

        /// <summary>
        /// 发送阿里云短信（使用预设模板）
        /// </summary>
        /// <param name="mobile">接收短信的手机号码（中国大陆11位）</param>
        /// <param name="values">模板参数列表（按{0}、{1}顺序替换）</param>
        /// <returns>阿里云短信发送响应对象（包含状态码和请求ID）</returns>
        /// <exception cref="ArgumentNullException">当mobile或values为null时抛出</exception>
        /// <exception cref="ArgumentException">当mobile格式错误或values参数数量不匹配时抛出</exception>
        public AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsResponse SendMobile(string mobile, List<string> values)
        {
            // 校验参数有效性
            if (string.IsNullOrEmpty(mobile) || values == null)
                throw new ArgumentNullException("手机号或模板参数不能为空");
            if (!Regex.IsMatch(mobile, @"^1[3-9]\d{9}$"))
                throw new ArgumentException("手机号格式错误，需为中国大陆11位号码");

            // 创建阿里云客户端
            AlibabaCloud.SDK.Dysmsapi20170525.Client client = CreateClient(aLiYun.AccessKeyId, aLiYun.AccessKeySecret);

            // 组装短信发送请求
            AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsRequest sendSmsRequest = new()
            {
                SignName = mobileOptions.SignName,            // 短信签名（需在阿里云备案）
                TemplateCode = mobileOptions.TemplateCode,    // 短信模板编码
                PhoneNumbers = mobile,                        // 接收号码
                TemplateParam = ReplaceUnknownParams(mobileOptions.TemplateParam, values).Replace("\\", ""),
            };

            // 发送短信并返回响应
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new();
            return client.SendSmsWithOptions(sendSmsRequest, runtime);
        }

        /// <summary>
        /// 使用AccessKey初始化阿里云短信服务客户端
        /// </summary>
        /// <param name="accessKeyId">阿里云访问密钥ID</param>
        /// <param name="accessKeySecret">阿里云访问密钥Secret</param>
        /// <returns>初始化完成的短信服务客户端</returns>
        private static AlibabaCloud.SDK.Dysmsapi20170525.Client CreateClient(string accessKeyId, string accessKeySecret)
        {
            AlibabaCloud.OpenApiClient.Models.Config config = new()
            {
                AccessKeyId = accessKeyId,       // 必填：阿里云账号AccessKey ID
                AccessKeySecret = accessKeySecret, // 必填：阿里云账号AccessKey Secret
                Endpoint = "dysmsapi.aliyuncs.com"  // 短信服务API域名（固定值）
            };
            return new AlibabaCloud.SDK.Dysmsapi20170525.Client(config);
        }

        /// <summary>
        /// 替换短信模板中的参数占位符（{0}、{1}等）
        /// </summary>
        /// <param name="input">原始模板参数字符串（如{"code":"{0}","time":"{1}"}</param>
        /// <param name="values">参数值列表（按顺序替换占位符）</param>
        /// <returns>替换后的参数字符串（JSON格式）</returns>
        /// <example>
        /// 输入：input="{"code":"{0}","time":"{1}"}", values=["1234","5分钟"]
        /// 输出：{"code":"1234","time":"5分钟"}
        /// </example>
        public static string ReplaceUnknownParams(string input, List<string> values)
        {
            for (int i = 0; i < values.Count; i++)
            {
                input = input.Replace("{" + i + "}", values[i]);
            }
            return input;
        }
    }
}
